package mysql.cs;

import mysql.MysqlPacket;
import mysql.MysqlPacketHeader;
import mysql.socket.SocketChannel;

import java.io.IOException;

/**
 * @ClassName PacketManager
 * @Description TODO
 * @Author fengk
 * @Date 2018/9/5 14:21
 */

public abstract class PacketManager {
    public static MysqlPacketHeader readHeader(SocketChannel ch, int len) throws IOException {
        MysqlPacketHeader header = new MysqlPacketHeader();
        header.encode(ch.read(len));
        return header;
    }

    public static MysqlPacketHeader readHeader(SocketChannel ch, int len, int timeout) throws IOException {
        MysqlPacketHeader header = new MysqlPacketHeader();
        header.encode(ch.read(len, timeout));
        return header;
    }

    public static byte[] readBytes(SocketChannel ch, int len) throws IOException {
        return ch.read(len);
    }

    public static byte[] readBytes(SocketChannel ch, int len, int timeout) throws IOException {
        return ch.read(len, timeout);
    }

    public static void writePkg(SocketChannel ch, byte[]... srcs) throws IOException {
        ch.write(srcs);
    }

    public static void writeBody(SocketChannel ch, byte[] body) throws IOException {
        writeBody0(ch, body, (byte) 0);
    }
    public static void writeBodyNext(SocketChannel ch, byte[] body) throws IOException {
        writeBody0(ch, body, (byte) 1);
    }


    public static void writeBody0(SocketChannel ch, byte[] body, byte packetSeqNumber) throws IOException {
        MysqlPacketHeader header = new MysqlPacketHeader();
        header.setPayloadLength(body.length);
        header.setSequenceId(packetSeqNumber);
        ch.write(header.decode(), body);
    }
}
